/*
 * testclient.cpp
 *
 *  Created on: Apr 14, 2011
 *      Author: Alan Mattila
 */

#include <QtGui>
#include <QMainWindow>

#include <iostream>

#include "testclient.h"
#include "../../../board/Board.h"
#include "../../NetworkClient.h"
#include "../../../misc/debug.h"


testclient::testclient(QWidget *parent = 0)
{
	TRACE("Calling testclient() default constructor\n");
	hostname = HOSTNAME;

	initWindow();
}


testclient::testclient(QWidget *parent, string hn)
{
	TRACE("");
	std::cout << "Calling testclient(string) constructor\n";
	hostname = hn;

	initWindow();
}


testclient::~testclient()
{
	if(client)
		delete client;

	// Connect PushButton
	if(actionConnect)
		delete actionConnect;

	// Close button
	if(actionClose)
		delete actionClose;

	if(moveButton)
		delete moveButton;
}


void testclient::initWindow(void)
{
	this->setFixedSize(300, 200);

	// Connect button
	actionConnect = new QPushButton(QString("Connect"), this);
	actionConnect->setGeometry(20, 40, 100, 30);
	actionConnect->show();

	// Close Button
	actionClose = new QPushButton(QString("Close"), this);
	actionClose->setGeometry(140, 40, 100, 30);
	actionClose->show();

	// Move button
	moveButton = new QPushButton(QString("Move"), this);
	moveButton->setGeometry(20, 100, 100, 30);
	moveButton->show();
	connect(moveButton, SIGNAL(clicked()), this, SLOT(TestMove()));

	client = new NetworkClient(hostname);
	tcpSocket = client->GetTcpSocket();

	board = client->GetBoard();
	std::cout << *board;

	TRACE("calling connect()\n");
	connect(actionConnect, SIGNAL(clicked()), this, SLOT(ConnectToServer()));
	connect(actionClose, SIGNAL(clicked()), this, SLOT(Close()));
	connect(client, SIGNAL(messageReceived(packetMessage_t)), this, SLOT(HandleMessage(packetMessage_t)));
	connect(client, SIGNAL(gameBoardReceived()), this, SLOT(HandleGameBoard()));
}


void testclient::ConnectToServer(void)
{
	if(client->ConnectToServer())
	{
		TRACE("Error connecting to server\n");
	}
}


void testclient::Close(void)
{
	close();
}


void testclient::HandleMessage(packetMessage_t message)
{
	if(message == IllegalMove)
	{
		TRACE("Received message: IllegalMove\n");

		// Need to make another move
	}
}


void testclient::HandleGameBoard(void)
{
	TRACE("Received updated game board\n");
	board = client->GetBoard();

	TRACE("Outputting the new game board\n");
	std::cout << *board;
}


void testclient::Disconnected(void)
{
	TRACE("");
	qDebug() << "disconnected() signal received";
}


void testclient::TestMove(void)
{
	// Make a test move
	client->MakeMove(1, 2, 2, 3);
}
